package com.springboot.java.design.lock;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 *   测试 读写锁
 */
@Slf4j
public class TestReadWriteLock {

    public static void main(String[] args) {

        ExecutorService executor = Executors.newFixedThreadPool(10);

        for (int i = 0; i < 10; i++) {

            executor.execute(new ReadWriteAdd());

        }

        executor.shutdown();

    }


}

class ReadWriteAdd implements Runnable{

    private static int num  = 0;

    ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    @Override
    public void run() {

        String threadName = Thread.currentThread().getName();

        // 读锁
        ReentrantReadWriteLock.ReadLock readLock = lock.readLock();
        // 写锁
        ReentrantReadWriteLock.WriteLock writeLock = lock.writeLock();

        //  获取读锁
        readLock.lock();

        System.out.println(threadName + " -- 获取读锁，当前num=" + num);
        // 释放读锁
        readLock.unlock();
        // 获取写锁
        writeLock.lock();
        System.out.println(threadName + " -- 获取写锁");
        num +=1;

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 获取读锁  这里还没有释放写锁 属于锁的降级
        readLock.lock();
        // 释放写锁
        System.out.println(threadName + " -- 释放写锁");
        writeLock.unlock();

        System.out.println(threadName + " -- 再次获取读锁，当前num="  + num);

        readLock.unlock();
    }
}
